package com.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.biz.BillBiz;
import com.biz.ChangyouVipBiz;
import com.biz.CustomerBiz;
import com.biz.SmsCodeAuthBiz;
import com.core.Result;
import com.core.ResultGenerator;
import com.entity.model.Bill;
import com.entity.model.ChangyouVip;
import com.entity.model.Customer;
import com.entity.model.SmsCodeAuth;
import com.sms.SmsUtil;
import com.util.HttpRequest;
import com.util.RandomStringGenerator;
import com.util.SystemConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.util.Base64;
import tk.mybatis.mapper.entity.Condition;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by CodeGenerator on 2017/08/21.
 */
@RestController("SmsController")
@RequestMapping("/api/smsSend")
public class SmsController {

    @Autowired
    private CustomerBiz customerBiz;

    @Autowired
    private ChangyouVipBiz changyouVipBiz;

    @Autowired
    private BillBiz billBiz;

    @Autowired
    private SmsCodeAuthBiz smsCodeAuthBiz;

    //小程序用户登录发送短信
    @RequestMapping(value = "/minaLogin")
    public Result minaLogin(@RequestParam String phone) {
        //删除已过期的短信验证码
        smsCodeAuthBiz.deleteExpiredTime();

        phone = phone.trim();
        if (StringUtils.isBlank(phone)) {
            return ResultGenerator.genFailResult("手机号不能为空");
        }
        return sendSms(phone);
    }

    //小程序用户登录发送短信
    @RequestMapping(value = "/thirdApi")
    public String thirdApi(@RequestParam Integer customerId, @RequestParam Integer billId) throws Exception {
        Customer customer = customerBiz.findById(customerId);
        Bill bill = billBiz.findById(billId);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> params = new HashMap<>();
        params.put("refno", bill.getBillNo());
        params.put("user_id", customer.getId());
        params.put("user_mobile", customer.getAccount());
        params.put("quantity", 1);
        params.put("price", bill.getBillFee());
        params.put("gross_amount", bill.getBillFee());
        params.put("rebate_amount", 300);
        params.put("order_time", formatter.format(bill.getCreateTime()));
        params.put("pay_time", formatter.format(bill.getPayDate()));

        String hourStr = "";
        String minuteStr = "";
        String secondStr = "";
        Calendar now = Calendar.getInstance();
        Integer hour = now.get(Calendar.HOUR_OF_DAY);
        if (hour < 10) {
            hourStr = "0" + hour.toString();
        } else {
            hourStr = hour.toString();
        }
        Integer minute = now.get(Calendar.MINUTE);
        if (minute < 10) {
            minuteStr = "0" + minute.toString();
        } else {
            minuteStr = minute.toString();
        }
        Integer second = now.get(Calendar.SECOND);
        if (second < 10) {
            secondStr = "0" + second.toString();
        } else {
            secondStr = second.toString();
        }
        String text = "" + hourStr + "9baAmjwJ" + minuteStr + "8LhjWTy9" + secondStr + "";
        /*byte[] textByte = text.getBytes("UTF-8");*/
        String sign = Base64.encode(text.getBytes("UTF-8"));
        String result = HttpRequest.sendPost("https://wxapp.yiluyouai.cn/integration/userPurchase", JSON.toJSONString(params), sign);
        if (JSONObject.parseObject(result).getString("code").equals("200")) {
            Condition condition = new Condition(ChangyouVip.class);
            condition.createCriteria().andIsNull("customerId");
            ChangyouVip changyouVip = changyouVipBiz.findByCondition(condition).get(0);
            SmsUtil.changyouMsg(customer.getAccount(), changyouVip.getCardNo(), changyouVip.getCardPwd());
            changyouVip.setCustomerId(customer.getId());
            changyouVipBiz.update(changyouVip);
        }
        return result;
    }

    //验证验证码是否正确
    @RequestMapping(value = "/authCode")
    public Result authCode(@RequestParam Integer smsId, @RequestParam String code, @RequestParam Integer customerId, @RequestParam String phone, String partner_id) throws Exception {
        if (StringUtils.isBlank(code)) {
            return ResultGenerator.genFailResult("验证码不能为空");
        }
        if (smsId == null) {
            return ResultGenerator.genFailResult("短信编号不能为空");
        }

        Condition condition = new Condition(SmsCodeAuth.class);
        condition.createCriteria().andEqualTo("id", smsId).andEqualTo("smsCode", code).andEqualTo("phone", phone);
        if (smsCodeAuthBiz.findByCondition(condition).size() == 0) {
            return ResultGenerator.genFailResult("验证码错误");
        }
        SmsCodeAuth smsCodeAuth = smsCodeAuthBiz.findByCondition(condition).get(0);
        if (smsCodeAuth.getId() > 0) {
            condition.createCriteria().andLessThan("expiredTime", new Date());
            smsCodeAuth = smsCodeAuthBiz.findByCondition(condition).get(0);
            if (smsCodeAuth.getId() > 0) {
                smsCodeAuthBiz.deleteById(smsCodeAuth.getId());
                Customer customer = customerBiz.findBy("account", phone);
                if (customer != null) {
                    if (partner_id != null && partner_id.equals("6dbe627a03b925cbcefdf6bc76b551a7")) {
                        customer.setParentBdId(13);
                        customerBiz.update(customer);
                    }

                    if (customer.getParentBdId() != null && customer.getParentBdId() == 13) {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Map<String, Object> params = new HashMap<>();
                        params.put("user_id", customer.getId());
                        params.put("user_mobile", customer.getAccount());
                        params.put("user_name", customer.getNickName().replace("\'", "").replace("\"", ""));
                        params.put("register_time", formatter.format(customer.getCreateTime()));

                        String hourStr = "";
                        String minuteStr = "";
                        String secondStr = "";
                        Calendar now = Calendar.getInstance();
                        Integer hour = now.get(Calendar.HOUR_OF_DAY);
                        if (hour < 10) {
                            hourStr = "0" + hour.toString();
                        } else {
                            hourStr = hour.toString();
                        }
                        Integer minute = now.get(Calendar.MINUTE);
                        if (minute < 10) {
                            minuteStr = "0" + minute.toString();
                        } else {
                            minuteStr = minute.toString();
                        }
                        Integer second = now.get(Calendar.SECOND);
                        if (second < 10) {
                            secondStr = "0" + second.toString();
                        } else {
                            secondStr = second.toString();
                        }
                        String text = "" + hourStr + "9baAmjwJ" + minuteStr + "8LhjWTy9" + secondStr + "";
                        byte[] textByte = text.getBytes("UTF-8");
                        String sign = Base64.encode(text.getBytes("UTF-8"));
                        HttpRequest.sendPost("https://wxapp.yiluyouai.cn/integration/userRegistration", JSON.toJSONString(params), sign);
                    }
                    return ResultGenerator.genSuccessResult(customer);
                }
                customer = customerBiz.findById(customerId);
                if (customer != null) {
                    Customer customer2 = customerBiz.findBy("account", phone);
                    if (customer2 != null) {
                        customer = customer2;
                    } else {
                        customer.setAccount(phone);
                        customer.setPassword("123456");
                        if (partner_id != null && partner_id.equals("6dbe627a03b925cbcefdf6bc76b551a7")) {
                            customer.setParentBdId(13);
                        }
                        customerBiz.update(customer);
                    }
                }

                if (customer.getParentBdId() != null && customer.getParentBdId() == 13) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Map<String, Object> params = new HashMap<>();
                    params.put("user_id", customer.getId());
                    params.put("user_mobile", customer.getAccount());
                    params.put("user_name", customer.getNickName().replace("\'", "").replace("\"", ""));
                    params.put("register_time", formatter.format(customer.getCreateTime()));

                    String hourStr = "";
                    String minuteStr = "";
                    String secondStr = "";
                    Calendar now = Calendar.getInstance();
                    Integer hour = now.get(Calendar.HOUR_OF_DAY);
                    if (hour < 10) {
                        hourStr = "0" + hour.toString();
                    } else {
                        hourStr = hour.toString();
                    }
                    Integer minute = now.get(Calendar.MINUTE);
                    if (minute < 10) {
                        minuteStr = "0" + minute.toString();
                    } else {
                        minuteStr = minute.toString();
                    }
                    Integer second = now.get(Calendar.SECOND);
                    if (second < 10) {
                        secondStr = "0" + second.toString();
                    } else {
                        secondStr = second.toString();
                    }
                    String text = "" + hourStr + "9baAmjwJ" + minuteStr + "8LhjWTy9" + secondStr + "";
                    byte[] textByte = text.getBytes("UTF-8");
                    String sign = Base64.encode(text.getBytes("UTF-8"));
                    HttpRequest.sendPost("https://wxapp.yiluyouai.cn/integration/userRegistration", JSON.toJSONString(params), sign);
                }

                return ResultGenerator.genSuccessResult(customer);
            } else {
                return ResultGenerator.genFailResult("验证码已过期,请重新发送");
            }
        } else {
            return ResultGenerator.genFailResult("内部错误");
        }
    }


    /**
     * @param phone 手机号
     * @return
     */
    private Result sendSms(String phone) {
        phone = phone.trim();
        if (StringUtils.isBlank(phone)) {
            return ResultGenerator.genFailResult("手机号不能为空");
        }
        String sixRandom = RandomStringGenerator.getRandomStringByLength(6);
        String str = SmsUtil.sendCode(phone, sixRandom);
        SmsCodeAuth smsCodeAuth = new SmsCodeAuth();
        if (str.equals("success")) {
            smsCodeAuth.setSmsCode(sixRandom);
            smsCodeAuth.setPhone(phone);
            smsCodeAuth.setExpiredTime((new Date(new Date().getTime() + 600000)));
            smsCodeAuthBiz.save(smsCodeAuth);
        }
        return ResultGenerator.genSuccessResult(smsCodeAuth.getId());
    }
}
